﻿namespace Rosieks.Web.Flow
{
    using System;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Web.Hosting;
    using Rosieks.Web.Flow.Metadata;

    public class PreApplicationStart
    {
        public static void Start()
        {
            PreApplicationStart.RegisterWebflowModels();
        }

        private static void RegisterWebflowModels()
        {
            string autoRegistration = ConfigurationManager.AppSettings["Webflow:AutoRegistration"];
            if (autoRegistration == null || !string.Equals("false", autoRegistration, StringComparison.InvariantCultureIgnoreCase))
            {
                PreApplicationStart.LoadAssemblies();

                var webflowModels = AppDomain.CurrentDomain
                    .GetAssemblies()
                    .SelectMany(a => a.GetExportedTypes())
                    .Where(t => typeof(WebflowModel).IsAssignableFrom(t))
                    .ToArray();
                    //.Where(t => t != typeof(WebflowModel) &&  !t.IsAbstract);

                foreach (var webflowModelType in webflowModels.Where(t => t != typeof(WebflowModel) && !t.IsAbstract))
                {
                    WebflowModel model = (WebflowModel)Activator.CreateInstance(webflowModelType);

                    HashtableWebflowCatalog.Instance.Register(model);
                }
            }
        }

        private static void LoadAssemblies()
        {
            var files = HostingEnvironment.VirtualPathProvider.GetDirectory("~/bin")
                .Files
                .Cast<VirtualFileBase>()
                .Select(f => HostingEnvironment.MapPath(f.VirtualPath))
                .Where(f => Path.GetExtension(f) == ".dll");

            foreach (var file in files)
            {
                Assembly.LoadFrom(file);
            }
        }
    }
}
